const express = require ('express')
const multer = require('multer')
const Category = require('../../models/Category')
const upload = multer({
    dest: __dirname + '/../../upload'
})


function router(app){
    const route = express.Router({
        mergeParams: true
    })

    // 获取资源列表
    route.get('/', async (req, res) => {
        let model = await req.Model.find().lean()
        if (req.Model.modelName == "Article"){
            model = await req.Model.find().populate('categories').lean()
        }
        res.send(model)
    })

    // 新建资源
    route.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 获取指定资源
    route.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id).lean()
        res.send(model)
    })

    // 修改指定资源
    route.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 删除指定资源
    route.delete('/:id', async (req, res) => {
        const result = await req.Model.findByIdAndRemove(req.params.id)
        res.send({
            message: "success"
        })
    })


    app.use('/admin/api/rest/:resource', (req, res, next) => {
        req.Model = require(`../../models/${req.params.resource}.js`)
        next()
    } , route)


    // 上传图片链接
    app.post('/admin/api/image/upload', upload.single('file'), (req, res) => {
        console.log('receive image request!')
        const file = req.file
        file.url = `http://www.sunwenliang.com/upload/${req.file.filename}`
        res.send(file)
    })
}

module.exports = router